package com.alinu.web.filter;

import com.alinu.settings.domain.User;
import com.alinu.utils.CommonUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author chenzuwei
 * @date 2021/3/15
 * @description 登录拦截器
 */
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;

        String path = httpServletRequest.getServletPath();

        if ("/login.jsp".equals(path) || "/settings/user/login.do".equals(path)) {
            chain.doFilter(request, response);
        } else {
            HttpSession session = httpServletRequest.getSession();

            User user = (User) session.getAttribute("user");

            // 判断session中是否有user对象，如果没有则需要重新登录
            if (CommonUtil.isNull(user)) {
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
            } else {
                chain.doFilter(request, response);
            }
        }

    }
}
